//
//  File.swift
//  hello
//
//  Created by 赵康 on 2024/11/11.
//

import Vapor
@preconcurrency import Redis

struct AuthMiddleware: Middleware {
	// 登录凭证过期时间 (7天)
  private let sessionExpiration: TimeAmount = .hours(7 * 24)
	
	func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
		print("Debug: AuthMiddleware - 收到请求")
		print("Debug: 请求路径: \(request.url.path)")
		print("Debug: Authorization: \(request.headers.first(name: "Authorization") ?? "无")")
		guard let sessionKey = request.headers.bearerAuthorization?.token else {
			return request.eventLoop.makeFailedFuture(Abort(.unauthorized, reason: "缺少会话信息"))
		}
		
		let redisSessionKey = RedisKey("session:\(sessionKey)")
		return request.redis.get(redisSessionKey).flatMap { userID in
			guard let userIDString = userID.string else {
				return request.eventLoop.makeFailedFuture(Abort(.unauthorized, reason: "会话无效"))
			}
			request.session.data["userID"] = userIDString
			
			// 延长会话有效期
			let _ = request.redis.expire(redisSessionKey, after: self.sessionExpiration)
			
			return next.respond(to: request)
		}
	}
}
